#define _GNU_SOURCE
#include "app_serial.h"
#include "log/log.h"

int App_Serial_Init(Device_t *dev)
{
    App_Serial_SetBaudRate(dev, BR_9600); //蓝牙初始波特率是9600
    App_Serial_SetParity(dev, Parity_None); //无校验
    App_Serial_SetStopBits(dev, StopBits_1);//1位停止位
    App_Serial_SetBlock(dev, NoBlock); //蓝牙未就绪不可以阻塞
    App_Serial_SetRaw(dev);
    tcflush(dev->fd, TCIOFLUSH);
    return 0;
}

int App_Serial_SetBaudRate(Device_t *dev, BaudRate br)
{
    struct termios attr = {0};
    tcgetattr(dev->fd, &attr);
    cfsetspeed(&attr, br);
    if(tcsetattr(dev->fd, TCSAFLUSH, &attr) == -1)
    {
        log_error("set baudrate failed");
        return -1;
    }
    log_debug("set baudrate success");
    return 0;
}
int App_Serial_SetParity(Device_t *dev, Parity parity)
{
    struct termios attr = {0};
    tcgetattr(dev->fd, &attr);
    attr.c_cflag &= ~(PARENB | PARODD);
    attr.c_cflag |= parity;
    if(tcsetattr(dev->fd, TCSAFLUSH, &attr) == -1)
    {
        log_error("set parity failed");
        return -1;
    }
    log_debug("set parity success");
    return 0;
}

int App_Serial_SetStopBits(Device_t *dev, StopBits sb)
{
    struct termios attr = {0};
    tcgetattr(dev->fd, &attr);
    attr.c_cflag &= ~CSTOPB;
    attr.c_cflag |= sb;
    if(tcsetattr(dev->fd, TCSAFLUSH, &attr) == -1)
    {
        log_error("set stopbits failed");
        return -1;
    }
    log_debug("set stopbits success");
    return 0;
}

int App_Serial_SetBlock(Device_t *dev, is_Block block)
{
    struct termios attr = {0};
    tcgetattr(dev->fd, &attr);
    if(block == Block)
    {
        attr.c_cc[VMIN] = 1;
        attr.c_cc[VTIME] = 0;
    }
    else
    {
        attr.c_cc[VMIN] = 0;
        attr.c_cc[VTIME] = 2;
    }
    if(tcsetattr(dev->fd, TCSAFLUSH, &attr) == -1)
    {
        log_error("set is_block failed");
        return -1;
    }
    log_debug("set is_block success");
    return 0;
}

int App_Serial_SetRaw(Device_t *dev)
{
    struct termios attr = {0};
    tcgetattr(dev->fd, &attr);
    cfmakeraw(&attr);
    if(tcsetattr(dev->fd, TCSAFLUSH, &attr) == -1)
    {
        log_error("set raw failed");
        return -1;
    }
    log_debug("set raw success");
    return 0;
}
